package com.mycompany.myapp.web.rest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.mycompany.myapp.IntegrationTest;
import com.mycompany.myapp.domain.StudentScore;
import com.mycompany.myapp.repository.StudentScoreRepository;
import com.mycompany.myapp.service.dto.StudentScoreDTO;
import com.mycompany.myapp.service.mapper.StudentScoreMapper;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import javax.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

/**
 * Integration tests for the {@link StudentScoreResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class StudentScoreResourceIT {

    private static final Long DEFAULT_SCORE = 1L;
    private static final Long UPDATED_SCORE = 2L;

    private static final Integer DEFAULT_SCORE_STATUS = 1;
    private static final Integer UPDATED_SCORE_STATUS = 2;

    private static final String ENTITY_API_URL = "/api/student-scores";
    private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

    private static Random random = new Random();
    private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

    @Autowired
    private StudentScoreRepository studentScoreRepository;

    @Autowired
    private StudentScoreMapper studentScoreMapper;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restStudentScoreMockMvc;

    private StudentScore studentScore;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static StudentScore createEntity(EntityManager em) {
        StudentScore studentScore = new StudentScore().score(DEFAULT_SCORE).scoreStatus(DEFAULT_SCORE_STATUS);
        return studentScore;
    }

    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static StudentScore createUpdatedEntity(EntityManager em) {
        StudentScore studentScore = new StudentScore().score(UPDATED_SCORE).scoreStatus(UPDATED_SCORE_STATUS);
        return studentScore;
    }

    @BeforeEach
    public void initTest() {
        studentScore = createEntity(em);
    }

    @Test
    @Transactional
    void createStudentScore() throws Exception {
        int databaseSizeBeforeCreate = studentScoreRepository.findAll().size();
        // Create the StudentScore
        StudentScoreDTO studentScoreDTO = studentScoreMapper.toDto(studentScore);
        restStudentScoreMockMvc
            .perform(
                post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(studentScoreDTO))
            )
            .andExpect(status().isCreated());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeCreate + 1);
        StudentScore testStudentScore = studentScoreList.get(studentScoreList.size() - 1);
        assertThat(testStudentScore.getScore()).isEqualTo(DEFAULT_SCORE);
        assertThat(testStudentScore.getScoreStatus()).isEqualTo(DEFAULT_SCORE_STATUS);
    }

    @Test
    @Transactional
    void createStudentScoreWithExistingId() throws Exception {
        // Create the StudentScore with an existing ID
        studentScore.setId(1L);
        StudentScoreDTO studentScoreDTO = studentScoreMapper.toDto(studentScore);

        int databaseSizeBeforeCreate = studentScoreRepository.findAll().size();

        // An entity with an existing ID cannot be created, so this API call must fail
        restStudentScoreMockMvc
            .perform(
                post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(studentScoreDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    void getAllStudentScores() throws Exception {
        // Initialize the database
        studentScoreRepository.saveAndFlush(studentScore);

        // Get all the studentScoreList
        restStudentScoreMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(studentScore.getId().intValue())))
            .andExpect(jsonPath("$.[*].score").value(hasItem(DEFAULT_SCORE.intValue())))
            .andExpect(jsonPath("$.[*].scoreStatus").value(hasItem(DEFAULT_SCORE_STATUS)));
    }

    @Test
    @Transactional
    void getStudentScore() throws Exception {
        // Initialize the database
        studentScoreRepository.saveAndFlush(studentScore);

        // Get the studentScore
        restStudentScoreMockMvc
            .perform(get(ENTITY_API_URL_ID, studentScore.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(studentScore.getId().intValue()))
            .andExpect(jsonPath("$.score").value(DEFAULT_SCORE.intValue()))
            .andExpect(jsonPath("$.scoreStatus").value(DEFAULT_SCORE_STATUS));
    }

    @Test
    @Transactional
    void getNonExistingStudentScore() throws Exception {
        // Get the studentScore
        restStudentScoreMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putNewStudentScore() throws Exception {
        // Initialize the database
        studentScoreRepository.saveAndFlush(studentScore);

        int databaseSizeBeforeUpdate = studentScoreRepository.findAll().size();

        // Update the studentScore
        StudentScore updatedStudentScore = studentScoreRepository.findById(studentScore.getId()).get();
        // Disconnect from session so that the updates on updatedStudentScore are not directly saved in db
        em.detach(updatedStudentScore);
        updatedStudentScore.score(UPDATED_SCORE).scoreStatus(UPDATED_SCORE_STATUS);
        StudentScoreDTO studentScoreDTO = studentScoreMapper.toDto(updatedStudentScore);

        restStudentScoreMockMvc
            .perform(
                put(ENTITY_API_URL_ID, studentScoreDTO.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(studentScoreDTO))
            )
            .andExpect(status().isOk());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeUpdate);
        StudentScore testStudentScore = studentScoreList.get(studentScoreList.size() - 1);
        assertThat(testStudentScore.getScore()).isEqualTo(UPDATED_SCORE);
        assertThat(testStudentScore.getScoreStatus()).isEqualTo(UPDATED_SCORE_STATUS);
    }

    @Test
    @Transactional
    void putNonExistingStudentScore() throws Exception {
        int databaseSizeBeforeUpdate = studentScoreRepository.findAll().size();
        studentScore.setId(count.incrementAndGet());

        // Create the StudentScore
        StudentScoreDTO studentScoreDTO = studentScoreMapper.toDto(studentScore);

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restStudentScoreMockMvc
            .perform(
                put(ENTITY_API_URL_ID, studentScoreDTO.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(studentScoreDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithIdMismatchStudentScore() throws Exception {
        int databaseSizeBeforeUpdate = studentScoreRepository.findAll().size();
        studentScore.setId(count.incrementAndGet());

        // Create the StudentScore
        StudentScoreDTO studentScoreDTO = studentScoreMapper.toDto(studentScore);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restStudentScoreMockMvc
            .perform(
                put(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(studentScoreDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithMissingIdPathParamStudentScore() throws Exception {
        int databaseSizeBeforeUpdate = studentScoreRepository.findAll().size();
        studentScore.setId(count.incrementAndGet());

        // Create the StudentScore
        StudentScoreDTO studentScoreDTO = studentScoreMapper.toDto(studentScore);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restStudentScoreMockMvc
            .perform(
                put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(studentScoreDTO))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void partialUpdateStudentScoreWithPatch() throws Exception {
        // Initialize the database
        studentScoreRepository.saveAndFlush(studentScore);

        int databaseSizeBeforeUpdate = studentScoreRepository.findAll().size();

        // Update the studentScore using partial update
        StudentScore partialUpdatedStudentScore = new StudentScore();
        partialUpdatedStudentScore.setId(studentScore.getId());

        partialUpdatedStudentScore.score(UPDATED_SCORE);

        restStudentScoreMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedStudentScore.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedStudentScore))
            )
            .andExpect(status().isOk());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeUpdate);
        StudentScore testStudentScore = studentScoreList.get(studentScoreList.size() - 1);
        assertThat(testStudentScore.getScore()).isEqualTo(UPDATED_SCORE);
        assertThat(testStudentScore.getScoreStatus()).isEqualTo(DEFAULT_SCORE_STATUS);
    }

    @Test
    @Transactional
    void fullUpdateStudentScoreWithPatch() throws Exception {
        // Initialize the database
        studentScoreRepository.saveAndFlush(studentScore);

        int databaseSizeBeforeUpdate = studentScoreRepository.findAll().size();

        // Update the studentScore using partial update
        StudentScore partialUpdatedStudentScore = new StudentScore();
        partialUpdatedStudentScore.setId(studentScore.getId());

        partialUpdatedStudentScore.score(UPDATED_SCORE).scoreStatus(UPDATED_SCORE_STATUS);

        restStudentScoreMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedStudentScore.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedStudentScore))
            )
            .andExpect(status().isOk());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeUpdate);
        StudentScore testStudentScore = studentScoreList.get(studentScoreList.size() - 1);
        assertThat(testStudentScore.getScore()).isEqualTo(UPDATED_SCORE);
        assertThat(testStudentScore.getScoreStatus()).isEqualTo(UPDATED_SCORE_STATUS);
    }

    @Test
    @Transactional
    void patchNonExistingStudentScore() throws Exception {
        int databaseSizeBeforeUpdate = studentScoreRepository.findAll().size();
        studentScore.setId(count.incrementAndGet());

        // Create the StudentScore
        StudentScoreDTO studentScoreDTO = studentScoreMapper.toDto(studentScore);

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restStudentScoreMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, studentScoreDTO.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(studentScoreDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithIdMismatchStudentScore() throws Exception {
        int databaseSizeBeforeUpdate = studentScoreRepository.findAll().size();
        studentScore.setId(count.incrementAndGet());

        // Create the StudentScore
        StudentScoreDTO studentScoreDTO = studentScoreMapper.toDto(studentScore);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restStudentScoreMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(studentScoreDTO))
            )
            .andExpect(status().isBadRequest());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithMissingIdPathParamStudentScore() throws Exception {
        int databaseSizeBeforeUpdate = studentScoreRepository.findAll().size();
        studentScore.setId(count.incrementAndGet());

        // Create the StudentScore
        StudentScoreDTO studentScoreDTO = studentScoreMapper.toDto(studentScore);

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restStudentScoreMockMvc
            .perform(
                patch(ENTITY_API_URL)
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(studentScoreDTO))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the StudentScore in the database
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void deleteStudentScore() throws Exception {
        // Initialize the database
        studentScoreRepository.saveAndFlush(studentScore);

        int databaseSizeBeforeDelete = studentScoreRepository.findAll().size();

        // Delete the studentScore
        restStudentScoreMockMvc
            .perform(delete(ENTITY_API_URL_ID, studentScore.getId()).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        List<StudentScore> studentScoreList = studentScoreRepository.findAll();
        assertThat(studentScoreList).hasSize(databaseSizeBeforeDelete - 1);
    }
}
